<%--
  Created by IntelliJ IDEA.
  User: 30919
  Date: 2025/8/26
  Time: 18:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>
<!-- SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
    :root {
        --bs-primary: #3b7ddd;
        --bs-primary-rgb: 59, 125, 221;
        --bs-success: #1cbb8c;
        --bs-success-rgb: 28, 187, 140;
        --bs-danger: #fc5b69;
        --bs-danger-rgb: 252, 91, 105;
        --bs-warning: #f7b84b;
        --bs-warning-rgb: 247, 184, 75;
        --bs-light-bg: #f5f7fa;
    }

    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border: none;
        margin-bottom: 1.5rem;
    }

    .card-header {
        background-color: #fff;
        border-bottom: 1px solid #eaeef1;
        padding: 1rem 1.25rem;
        font-weight: 600;
        color: #2c3e50;
    }

    .table-container {
        background-color: #fff;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .table th {
        background-color: var(--bs-light-bg);
        color: #2c3e50;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-top: none;
    }

    .table td {
        padding: 0.75rem 1rem;
        vertical-align: middle;
    }

    .status-badge {
        padding: 0.35em 0.65em;
        border-radius: 0.25rem;
        font-size: 0.75em;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .bg-enabled {
        background-color: rgba(var(--bs-success-rgb), 0.15);
        color: var(--bs-success);
    }

    .bg-disabled {
        background-color: rgba(var(--bs-danger-rgb), 0.15);
        color: var(--bs-danger);
    }

    .action-btn {
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.875rem;
    }

    .search-box {
        position: relative;
    }

    .search-box .form-control {
        border-radius: 1.5rem;
        padding-left: 2.5rem;
    }

    .search-box .bi {
        position: absolute;
        left: 1rem;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        z-index: 10;
    }

    /* 动画效果 */
    .fade-in {
        animation: fadeIn 0.3s ease-in;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">XTEDU管理系统 - 菜单管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
        </div>
    </div>
</div>

<!-- 操作卡片 -->
<div class="card fade-in">
    <div class="card-body">
        <div class="row align-items-center g-3">
            <div class="col-md-6">
                <div class="search-box">
                    <i class="bi bi-search"></i>
                    <input type="text" class="form-control" placeholder="搜索菜单名称..." id="searchInput">
                </div>
            </div>
            <div class="col-md-6 text-md-end">
                <!-- 查询按钮 -->
                <button class="btn btn-outline-secondary" id="searchBtn">
                    <i class="bi bi-search me-1"></i>查询
                </button>
                <!-- 添加菜单按钮 -->
                <button class="btn btn-primary me-2" onclick="window.location.href='maintainnavigation/addnavigation'">
                    <i class="bi bi-plus-circle me-1"></i>添加菜单
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 数据表格 -->
<div class="table-container fade-in">
    <div class="table-responsive">
        <table class="table table-hover" id="menuTable">
            <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">父级ID</th>
                <th scope="col">菜单名称</th>
                <th scope="col">路径</th>
                <th scope="col">图标</th>
                <th scope="col">状态</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <tbody>
            <c:choose>
                <c:when test="${not empty menuItems}">
                    <c:forEach var="item" items="${menuItems}">
                        <tr>
                            <td>${item.id}</td>
                            <td>${item.pid}</td>
                            <td>${item.name}</td>
                            <td>${item.path}</td>
                            <td>
                                <c:if test="${not empty item.icon}">
                                    <i class="${fn:contains(item.icon, ' ') ? item.icon : 'bi '.concat(item.icon)}"></i>
                                </c:if>
                            </td>
                            <td>
                                <span class="status-badge ${item.state == true ? 'bg-enabled' : 'bg-disabled'}"
                                      data-id="${item.id}" data-state="${item.state}">
                                        ${item.state == true ? '启用' : '禁用'}
                                </span>

<%--                                <div class="form-check form-switch">--%>
<%--                                    <input class="form-check-input" type="checkbox" role="switch" id="${item.id}" checked="${item.state}">--%>
<%--                                </div>--%>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary action-btn"
                                        onclick="editMenuItem(${item.id})">
                                    <i class="bi bi-pencil me-1"></i>编辑
                                </button>
                                <button class="btn btn-sm btn-outline-danger action-btn"
                                        onclick="deleteMenuItem(${item.id}, '${item.name}')">
                                    <i class="bi bi-trash me-1"></i>删除
                                </button>
                            </td>
                        </tr>
                    </c:forEach>
                </c:when>
                <c:otherwise>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            <i class="bi bi-inbox display-4 d-block mb-2"></i>
                            暂无菜单数据
                        </td>
                    </tr>
                </c:otherwise>
            </c:choose>
            </tbody>
        </table>
    </div>
</div>
<!-- 在表格后面添加分页控件 -->
<c:if test="${not empty menuItems && menuItems.size() > 0}">
    <nav aria-label="Menu navigation">
        <ul class="pagination justify-content-center mt-4" id="menuPagination">
            <li style="flex-basis: 100%; height: 0;"></li>
            <!-- 这里需要添加分页按钮 -->
        </ul>

    </nav>
</c:if>
<%-- 弹出窗口自动消失--%>
<div class="modal fade" id="autoCloseModal" data-bs-autohide="true" data-bs-delay="3000" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                此弹框将在3秒后自动关闭
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const tableRows = document.querySelectorAll('#menuTable tbody tr');

        function performSearch() {
            const searchText = searchInput.value.toLowerCase().trim();

            tableRows.forEach(row => {
                const menuName = row.cells[2].textContent.toLowerCase();
                if (menuName.includes(searchText) || searchText === '') {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }

        searchInput.addEventListener('keyup', function (e) {
            if (e.key === 'Enter') {
                performSearch();
            } else {
                performSearch(); // 实时搜索
            }
        });

        searchBtn.addEventListener('click', performSearch);
    });

    // 更新菜单状态
    function updateMenuItemState(id, state, element) {
        // 使用URLSearchParams
        const params = new URLSearchParams();// 创建一个URLSearchParams对象
        params.append('id', id);
        params.append('action', 'update');
        params.append('state', state);
        console.log("发送更新数据："+ params.toString());
        fetch('delnavigation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString()
        })
            .then(response => response.json())
            .then(data => {
                console.log("返回数据："+ data);
                if (data.success) {
                    element.setAttribute('data-state', state);
                    if (state === true) {
                        element.classList.remove('bg-disabled');
                        element.classList.add('bg-enabled');
                        element.textContent = '启用';
                    } else {
                        element.classList.remove('bg-enabled');
                        element.classList.add('bg-disabled');
                        element.textContent = '禁用';
                    }
                } else {
                    alert('更新状态失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新状态时发生错误');
            });
    }

    // 编辑菜单
    function editMenuItem(id) {
        window.location.href = 'maintainnavigation/updatenavigation?id=' + id;
    }

    // 删除菜单 - 使用SweetAlert2美化提示
    function deleteMenuItem(id, name) {
        // 使用SweetAlert2替代原生confirm
        Swal.fire({
            title: '确认删除',
            html: '您确定要删除菜单 <strong>' + name + '</strong> 吗？<br>此操作不可恢复。',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            customClass: {
                popup: 'animated fadeIn'
            },
            backdrop: 'rgba(0,0,0,0.4)',
            showClass: {
                popup: 'animate__animated animate__fadeInDown'
            },
            hideClass: {
                popup: 'animate__animated animate__fadeOutUp'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // 用户确认删除
                showLoading('正在删除中...');

                const params = new URLSearchParams();
                params.append('id', id);
                params.append('action', 'delete');

                fetch('delnavigation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: params.toString()
                })
                    .then(response => response.json())
                    .then(data => {
                        Swal.close(); // 关闭加载提示

                        if (data.success) {
                            // 显示成功提示
                            showSuccess('删除成功').then(() => {
                                location.reload(); // 重新加载页面
                            });
                        } else {
                            showError('删除失败: ' + (data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        Swal.close(); // 关闭加载提示
                        console.error('Error:', error);
                        showError('删除时发生错误: ' + error.message);
                    });
            }
        });
    }

    // 显示加载中的提示
    function showLoading(message) {
        return Swal.fire({
            title: '请稍候',
            html: message,
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    }

    // 显示成功提示
    function showSuccess(message) {
        return Swal.fire({
            title: '成功',
            text: message,
            icon: 'success',
            confirmButtonColor: '#3085d6',
            confirmButtonText: '2秒后自动关闭',
            timer: 2000, // 2秒后自动关闭
            customClass: {
                popup: 'animated fadeIn'
            }
        });
    }

    // 显示错误提示
    function showError(message) {
        return Swal.fire({
            title: '错误',
            html: message,
            icon: 'error',
            confirmButtonColor: '#d33',
            confirmButtonText: '2秒后自动关闭',
            timer: 2000,// 2秒后自动关闭
            customClass: {
                popup: 'animated fadeIn'
            }
        });
    }

</script>
<script>
    $(document).ready(function() {
        // 分页功能实现
        const itemsPerPage = 8;
        const $rows = $('#menuTable tbody tr').not(':has(td[colspan])'); // 排除"暂无数据"行
        const totalItems = $rows.length;

        if (totalItems <= itemsPerPage) {
            return; // 数据不足一页，不需要分页
        }

        const totalPages = Math.ceil(totalItems / itemsPerPage);
        let currentPage = 1;

        // 初始化分页
        initPagination();
        showPage(1);

        function initPagination() {
            const $pagination = $('#menuPagination');
            $pagination
                .empty();

            // 添加页码信息
            // $pagination
            //     .append(
            //         '<li class="page-item disabled">' +
            //         '<span class="page-link">共 ' + totalItems + ' 条记录</span>' +
            //         '</li>'
            //     );

            // 添加上一页按钮
            $pagination
                .append(
                    '<li class="page-item" id="prevPage">' +
                    '<a class="page-link" href="javascript:void(0)" aria-label="Previous">' +
                    '<span aria-hidden="true">&laquo;</span>' +
                    '</a>' +
                    '</li>'
                );

            // 添加页码按钮
            for (let i = 1; i <= totalPages; i++) {
                $pagination
                    .append(
                        '<li class="page-item page-number' + (i === 1 ? ' active' : '') + '">' +
                        '<a class="page-link" href="javascript:void(0)" data-page="' + i + '">' + i + '</a>' +
                        '</li>'
                    );
            }

            // 添加下一页按钮
            $pagination
                .append(
                    '<li class="page-item" id="nextPage">' +
                    '<a class="page-link" href="javascript:void(0)" aria-label="Next">' +
                    '<span aria-hidden="true">&raquo;</span>' +
                    '</a>' +
                    '</li>'
                );

            // 绑定事件
            $('#prevPage').click(function() {
                if (currentPage > 1) {
                    showPage(currentPage - 1);
                }
            });

            $('#nextPage').click(function() {
                if (currentPage < totalPages) {
                    showPage(currentPage + 1);
                }
            });

            $('.page-number a').click(function() {
                const page = parseInt($(this).data('page'));
                showPage(page);
            });
        }

        function showPage(page) {
            currentPage
                = page;

            // 隐藏所有行
            $rows
                .hide();

            // 显示当前页的行
            const startIndex = (page - 1) * itemsPerPage;
            const endIndex = Math.min(startIndex + itemsPerPage, totalItems);

            for (let i = startIndex; i < endIndex; i++) {
                $($rows[i]).show();
            }

            // 更新分页状态
            updatePaginationState();
        }

        function updatePaginationState() {
            // 更新页码按钮状态
            $('.page-number').removeClass('active');
            $(`.page-number:has(a[data-page="${currentPage}"])`).addClass('active');

            // 更新上一页/下一页按钮状态
            $('#prevPage').toggleClass('disabled', currentPage === 1);
            $('#nextPage').toggleClass('disabled', currentPage === totalPages);
        }
    });
</script>
<jsp:include page="footer.jsp"/>